// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Crc16.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Hardware.DAC
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;

    /// <summary>
    /// Static class instance for generating CRC-16 values
    /// </summary>
    public static class Crc16
    {
        /// <summary>
        /// The CRC-16 polynomial
        /// </summary>
        private const int Crc16Polynomial = 0xA001;

        /// <summary>
        /// The CRC-16 table
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", 
            Justification = "Table values must be computed")]
        private static int[] crc16Table = new int[256];

        /// <summary>
        /// Initializes static members of the Crc16 class.
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", 
            Justification = "Table values must be computed")]
        static Crc16()
        {
            ushort value;
            ushort temp;

            for (ushort i = 0; i < crc16Table.Length; i++)
            {
                value = 0;
                temp = i;

                for (byte j = 0; j < 8; j++)
                {
                    if (((value ^ temp) & 0x0001) != 0)
                    {
                        value = (ushort)((value >> 1) ^ Crc16Polynomial);
                    }
                    else
                    {
                        value >>= 1;
                    }

                    temp >>= 1;
                }

                crc16Table[i] = value;
            }
        }

        /// <summary>
        /// Computes the has value for the specified data
        /// </summary>
        /// <param name="data">List of data</param>
        /// <param name="startIndex">Start index within data</param>
        /// <param name="length">Count of bytes to compute hash over</param>
        /// <returns>Computed CRC-16 value</returns>
        public static ushort ComputeHash(IList<byte> data, int startIndex, int length)
        {
            ushort calculatedHash = 0;

            if (data != null)
            {
                if (startIndex >= data.Count)
                {
                    throw new ArgumentOutOfRangeException();
                }

                if (length + startIndex > data.Count)
                {
                    throw new ArgumentOutOfRangeException();
                }

                for (int i = 0; i < length; i++)
                {
                    byte j = (byte)(calculatedHash ^ data[startIndex + i]);
                    calculatedHash = (ushort)((calculatedHash >> 8) ^ crc16Table[j]);
                }
            }

            return calculatedHash;
        }
    }
}
